<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onLoad, onReachBottom, onShow, onUnload } from "@dcloudio/uni-app";
import { useList } from "@/hooks/page";
import { usePageScroll } from "@/hooks/scroll";
import {
  live_course_now_header_api,
  live_course_list_api,
} from "@/package/mall/api/guider_home";
import { data_api } from "@/api/my";
import { EV_LOGIN, EV_ORDER } from "@/constant/event";
import { Account } from "@/utils/account";
import { AppData } from "@/utils/app";
import { autoTask } from "@/utils/timer";
import { Date } from "@/utils/date";
import { numToHour } from "@/utils/number";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import NavBack from "@/components/nav/back.vue";
import NavBar from "@/components/nav/bar.vue";
import NavBg from "@/components/nav/bg.vue";
import NavSpace from "@/components/nav/space.vue";
import SwipeDot from "@/components/swipe/dot.vue";
import IndexLiveItem from "@/pages/index/components/index-live-item.vue";
import PageSticky from "@/components/page/sticky.vue";
import ListTypeItem from "./components/list-type-item.vue";
import ListLiveItem from "./components/list-live-item.vue";
import ListMore from "@/components/list/more.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad(() => {
  live_course_now_header_api().then((resp) => {
    liveList.value = resp.items;
  });

  reloadList().then(() => {
    autoTaskStop = autoTask({ delay: 1000, immediate: true }, () => {
      const current = Date.getDate();
      const timestamp = current.unix();

      listData.value = listData.value.map((i) => {
        const start_time = Date.getDate(i.start_time * 1000);
        if (timestamp > i.end_time) {
          // 已结束
          i.live_state = 2;
          i.start_time_str = `${start_time.format("YYYY年M月D日 HH:mm")}`;
        } else if (timestamp < i.start_time) {
          // 未开始
          i.live_state = 0;
          const start_time_str = start_time.format(Date.ftDate);
          if (start_time_str === current.format(Date.ftDate)) {
            i.start_state = 1; // 今天
            i.start_time_arr = numToHour(i.start_time - timestamp).split(":");
          } else if (
            start_time_str === current.add(1, "day").format(Date.ftDate)
          ) {
            i.start_state = 2; // 明天
            i.start_time_str = `明天 ${start_time.format("HH:mm")}`;
          } else {
            i.start_state = 0;
            i.start_time_str = `${start_time.format("YYYY年M月D日 HH:mm")}`;
          }
        } else {
          // 直播中
          i.live_state = 1;
          i.start_time_str = `${start_time.format("YYYY年M月D日 HH:mm")}`;
        }
        return i;
      });
    });
  });

  Account.isLogin && reloadMyData();
  uni.$on(EV_LOGIN, evLoginCallback);
  uni.$on(EV_ORDER, evOrderCallback);
});
onShow(() => (myData.isVip = AppData.userData.is_vip_member === 1));
const { pageIsScroll, onPageScroll } = usePageScroll(() => {
  listLoadMore.value = listData.value.length > 1;
});
onReachBottom(() => loadMoreList());
onUnload(() => {
  autoTaskStop?.();
  uni.$off(EV_LOGIN, evLoginCallback);
  uni.$off(EV_ORDER, evOrderCallback);
});

const liveIndex = ref(0);
const liveList = ref<any[]>([]);
const liveClick = () => {
  const live = liveList.value[liveIndex.value];
  if (live.type === 3) {
    const fn = (isLogin: boolean) => {
      // 已购买
      if (myDataLiveList.value.includes(live.id))
        return Router.navigateToOrRedirectTo(isLogin, live.url);

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content: "该课程为付费直播课，需要购买后才能观看哦，是否购买该课程？",
          confirmText: "前往购买",
        },
        () => {
          Router.navigateTo(`/package/mall/pages/live/detail?id=${live.id}`);
        }
      );
    };

    Account.isLogin
      ? fn(false)
      : Account.login(() => {
          reloadMyData().then(() => fn(true));
        });
  } else {
    Account.checkLogin((isLogin) => {
      const fn = () => {
        Router.navigateToOrRedirectTo(isLogin, live.url);
      };

      if (live.type !== 4) return fn();

      // 是 VIP
      if (AppData.userData.is_vip_member === 1) return fn();

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content:
            "该课程为VIP专属直播课，需要开通导游VIP才能观看哦，是否开通？",
          confirmText: "开通导游VIP",
        },
        () => {
          Router.navigateTo("/package/mall/pages/vip/index");
        }
      );
    });
  }
};

const queryData = { type: 0 };

const typeList = ref(["全部直播课", "未开始", "全部回放", "已结束"]);
const typeClick = (index: number) => {
  queryData.type = index;
  reloadList();
};

const liveClick2 = (index: number) => {
  const live = listData.value[index];

  // 已结束、不支持回放
  if (live.live_state === 2 && live.is_can_playback !== 1) return;

  if (live.type === 3) {
    const fn = (isLogin: boolean) => {
      // 已购买
      if (myDataLiveList.value.includes(live.id))
        return live.live_state === 0
          ? Toast.show("直播未开始，请耐心等待哦~")
          : Router.navigateToOrRedirectTo(isLogin, live.url);

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content: "该课程为付费直播课，需要购买后才能观看哦，是否购买该课程？",
          confirmText: "前往购买",
        },
        () => {
          Router.navigateTo(`/package/mall/pages/live/detail?id=${live.id}`);
        }
      );
    };

    Account.isLogin
      ? fn(false)
      : Account.login(() => {
          reloadMyData().then(() => fn(true));
        });
  } else {
    Account.checkLogin((isLogin) => {
      const fn = () => {
        live.live_state === 0
          ? Toast.show("直播未开始，请耐心等待哦~")
          : Router.navigateToOrRedirectTo(isLogin, live.url);
      };

      if (live.type !== 4) return fn();

      // 是 VIP
      if (AppData.userData.is_vip_member === 1) return fn();

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content:
            "该课程为VIP专属直播课，需要开通导游VIP才能观看哦，是否开通？",
          confirmText: "开通导游VIP",
        },
        () => {
          Router.navigateTo("/package/mall/pages/vip/index");
        }
      );
    });
  }
};

const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return live_course_list_api({ ...query, ...toRaw(queryData) });
  });

const myData = reactive({ isVip: false });
const myDataLiveList = ref<number[]>([]);

const reloadMyData = () => {
  return data_api<{ live_course?: number[] }>({
    includes: "live_course",
  }).then((resp) => {
    myDataLiveList.value = resp.live_course || [];
  });
};
const evLoginCallback = (e: { type: "cancel" }) => {
  console.info(`触发事件：${EV_LOGIN}`, e);
  e.type === "cancel" || reloadMyData();
};
const evOrderCallback = (e: { type: "pay" }) => {
  console.info(`触发事件：${EV_ORDER}`, e);
  e.type === "pay" || reloadMyData();
};

let autoTaskStop: (() => void) | undefined = undefined;
const popupModal = ref<InstanceType<typeof PopupModal>>();
</script>

<template>
  <NavBack />
  <NavBar title="直播课" />
  <NavBg :retract="pageIsScroll" url="/package/mall/static/live-list-bg.png" />
  <NavSpace />

  <view class="list-live">
    <swiper
      class="list-live-swipe"
      circular
      autoplay
      @change="(e) => (liveIndex = e.detail.current)"
    >
      <swiper-item v-for="i of liveList" :key="i.id">
        <view class="list-live-item" @click="liveClick">
          <IndexLiveItem :info="i" />
        </view>
      </swiper-item>
    </swiper>
    <view class="list-live-dot">
      <SwipeDot
        v-model="liveIndex"
        :total="liveList.length"
        color="#ff7900"
        backgroundColor="rgba(255, 121, 0, 0.2)"
      />
    </view>
  </view>

  <PageSticky customNav background="#f9f9f9">
    <view class="list-type">
      <view
        class="list-type-item"
        v-for="(i, d) of typeList"
        :key="d"
        @click="typeClick(d)"
      >
        <ListTypeItem :text="i" :isActive="queryData.type === d" />
      </view>
    </view>
  </PageSticky>

  <view class="list-data">
    <view class="list-data-wrapper">
      <view
        class="list-data-item"
        v-for="(i, d) of listData"
        :key="i.id"
        @click="liveClick2(d)"
      >
        <ListLiveItem
          :info="i"
          :isPay="i.type === 4 ? myData.isVip : myDataLiveList.includes(i.id)"
        />
      </view>
    </view>
    <ListMore v-if="listLoadMore" :status="listStatus" />
  </view>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  padding-top: 40rpx;
}

.list-live {
  position: relative;
  padding-bottom: 28rpx;
  margin-bottom: 40rpx;

  .list-live-swipe {
    height: 212rpx;
    margin: 0 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .list-live-dot {
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
  }
}

.list-type {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding-left: 30rpx;

  .list-type-item {
    margin-right: 60rpx;
  }
}

.list-data {
  .list-data-wrapper {
    padding-top: 20rpx;
  }

  .list-data-item {
    margin: 0 30rpx 20rpx;
  }
}
</style>